package com.fourth_groups.shopping121store.ui.sight.adapter;

import android.os.Handler;
import android.os.Message;
import android.support.v4.view.ViewPager;
import android.support.v4.widget.SwipeRefreshLayout;
import android.view.MotionEvent;
import android.view.View;
import android.widget.ImageView;

import java.util.List;

/**
 * Created by Administrator on 2016/9/10.
 */
public class AutoRunThread implements Runnable {
    private int prePosition = 0;
    private Handler mHandler;
    ViewPager mVp;

    private long delayTime = 2000;
    private boolean isStart = false;
    private List<ImageView> imageViews;




    public AutoRunThread(ViewPager mVp, Handler mHandler, List<ImageView> imageViews) {
        this.mVp = mVp;
        this.mHandler = mHandler;
        this.imageViews=imageViews;

    }


    public void startRun() {
        if (!isStart) {
            mHandler.removeCallbacks(this);
            isStart = true;
            mHandler.postDelayed(this, delayTime);
        }
    }

    public void stopRun() {
        if (isStart) {
            isStart = false;
            mHandler.removeCallbacks(this);
        }
    }

    @Override
    public void run() {
        int currentItem = mVp.getCurrentItem();
        Message msg = Message.obtain();
        msg.what = 2;
        msg.arg1 = ++currentItem;
        mHandler.sendMessage(msg);
        mHandler.postDelayed(this, delayTime);
    }

    public void listener(){
        mVp.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
            }

            @Override
            public void onPageSelected(int position) {
                prePosition = position % imageViews.size();
            }

            @Override
            public void onPageScrollStateChanged(int state) {
            }
        });

        //处理Viewpage的触摸事件
        mVp.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View view, MotionEvent motionEvent) {
                switch (motionEvent.getAction()) {
                    case MotionEvent.ACTION_DOWN:
                        stopRun();
                        break;
                    case MotionEvent.ACTION_UP:
                        startRun();
                        break;
                }
                return false;
            }
        });
    }


    public void startRun(SwipeRefreshLayout mSrl) {
        SwipeRefreshLayout msr = mSrl;
        msr.setEnabled(false);
        if (!isStart) {
            mHandler.removeCallbacks(this);
            isStart = true;
            mHandler.postDelayed(this, delayTime);
        }
    }
}